package com.kkb.service;

import com.kkb.mapper.MenuMapper;
import com.kkb.mapper.RoleMapper;
import com.kkb.mapper.RoleMenuMapper;
import com.kkb.pojo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lxy
 * @create 2022-03-20 13:35
 */

@Service
public class RoleService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMapper roleMapper;

    //这个是在service层里利用现成sql多次访问数据库，得到数据
    //这里忘记在查询的菜单状态是要显示0(不被禁用)
    //以及通过用户获取用户所在的角色状态是否是0(正常),1(禁用)
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public List<Menu> getMenuListByRid(Integer rid) {
        Role role = roleMapper.selectByPrimaryKey(rid);
        if (role.getR_state() != 0) {
            return new ArrayList<Menu>();
        }
        RoleMenuExample roleMenuExample = new RoleMenuExample();
        MenuExample menuExample = new MenuExample();
        RoleMenuExample.Criteria criteria = roleMenuExample.createCriteria();
        MenuExample.Criteria criteria1 = menuExample.createCriteria();
        criteria.andR_idEqualTo(rid);
        List<RoleMenu> roleMenus = roleMenuMapper.selectByExample(roleMenuExample);
        List<Integer> midList = new ArrayList<>();
        for (RoleMenu roleMenu : roleMenus) {
            midList.add(roleMenu.getM_id());
        }
        criteria1.andM_idIn(midList);
        //状态0表示此菜单不被禁用
        criteria1.andM_stateEqualTo(0);
        List<Menu> menuList = menuMapper.selectByExample(menuExample);
        return menuList;
    }


    //这个是直接多表联查，直接在xml文件里写了查询语句，直接调用
    //这里没有涉及对菜单状态的筛选，所以不用
    @Transactional(propagation = Propagation.REQUIRED,readOnly = true)
    public List<Menu> getMenuListByRid1(Integer rid){
        List<Menu> menuList = menuMapper.queryMenuByRoleId(rid);
        return menuList;
    }

}
